﻿using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Atmk.WaterMeter.MIS.Commons;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.WeiXin;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository.WeiXin;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Atmk.WaterMeter.MIS.Entities.Models;
using NLog;

namespace Atmk.WaterMeter.MIS.Logic.WeiXin
{

    public class WxRechargeRecordLogic : IWxRechargeRecordLogic
    {
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly IAccountRepository _accountRepository;
        private readonly IMeterRepository _meterRepository;
        private readonly IOwnerRepository _ownerRepository;
        private readonly IRefillRepository _refillRepository;
        private readonly IWxRechargeRepositoryRead _wxRechargeRead;
        private readonly IWxRechargeRepositoryWrite _wxRechargeWrite;


        public WxRechargeRecordLogic(
            IAccountRepository accountRepository,
            IOwnerRepository ownerRepository,
            IMeterRepository meterRepository,
            IRefillRepository refillRepository,
            IWxRechargeRepositoryRead wxRechargeRead,
            IWxRechargeRepositoryWrite wxRechargeWrite
        )
        {
            _accountRepository = accountRepository;
            _ownerRepository = ownerRepository;
            _meterRepository = meterRepository;
            _refillRepository = refillRepository;
            _wxRechargeWrite = wxRechargeWrite;
            _wxRechargeRead = wxRechargeRead;
        }

        /// <summary>
        /// 创建订单记录
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="meterNumber"></param>
        /// <param name="out_trade_no"></param>
        /// <param name="amount"></param>
        /// <returns></returns>
        public BooleanResult CreateOrderRecored(string openid, string meterNumber, string out_trade_no, int amount)
        {
            var result = new BooleanResult { Success = false };
            var money = amount * 0.01m;
            try
            {
                //获取业主、水表、账户的id
                var owner = _ownerRepository.GetOwnersByMeterNo(meterNumber).First();
                //var accounts = _accountRepository.GetAccounts(owner.Id);
                //if (accounts.Count == 0)
                //{
                //    result.ErrorMessage = @"水表没有开户,请开通账户后，再进行充值";
                //}
                using (var _context = new atmk_wmdb_devContext())
                {
                    var orderDetail_owner=_context.OrderDetail.Where(m => m.OwnerId == owner.Id).ToList();
                    var balance = Convert.ToDecimal(orderDetail_owner.Sum(m => m.Money));
                    var order = new WxSrOrderRecords
                    {
                        OpenId = openid,
                        OutTradeNo = out_trade_no,
                        OwnerId = owner.Id,
                        AccountId = owner.Id,
                        HouseNumber = owner.HouseNumber,
                        Number = meterNumber,
                        RefillSum = money,
                        LastBalance = balance,
                        ShouldPayment = balance > 0 ? 0: balance
                    };
                
                try
                {
                    result.Success = _wxRechargeWrite.AddOrder(order);
                    if (!result.Success)
                        result.ErrorMessage = "添加表单数据失败";
                    result.Message = order.Id;
                }
                catch (Exception e)
                {
                    _logger.Error(e);
                    result.ErrorMessage = e.Message;
                }
                }
            }
            catch (Exception e)
            {
                _logger.Error(e);
                result.ErrorMessage = e.Message;
            }
            return result;
        }

        /// <summary>
        /// 通过订单信息充值
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="out_trade_no"></param>
        /// <returns></returns>
        public BooleanResult RechargeAccount(string openid, string out_trade_no)
        {
            var result = new BooleanResult { Success = false };
            try
            {
                var wxSrOrder = _wxRechargeRead.SelectOrder(openid, out_trade_no);
                var refillRecord = new RefillRecords
                {
                    OwnerId = wxSrOrder.OwnerId,
                    AccountId = wxSrOrder.AccountId,
                    StaffId = wxSrOrder.OpenId,
                    LastBalance = wxSrOrder.LastBalance,
                    ShouldPayment = wxSrOrder.ShouldPayment,
                    RefillSum = wxSrOrder.RefillSum,
                    RefillType = (int)AmountChangedUpMode.充值,
                    Rescind = 0,
                    RefillMessage = "微信小程序缴费"
                };
                if (_refillRepository.Add(refillRecord) > 0)
                {
                    //修改金额
                    //var upAcc = _accountRepository;
                    //var account = _accountRepository.FindAll<Account>().First(o => o.Id.ToString() == wxSrOrder.AccountId);
                    var account = new { Balance=0, Arrears=0 };
                    //实际金额=实收金额+余额-欠款
                    var value = wxSrOrder.RefillSum + account.Balance - account.Arrears;
                    //account.Arrears = 0;
                    //account.Balance = value;
                    result.Success = _accountRepository.Update(account) > 0;

                }
                if (result.Success)
                    UpdataOrderState(openid, out_trade_no, OrderStatus.Finish);
                return result;
            }
            catch (Exception e)
            {
                _logger.Error(e);
                result.ErrorMessage = e.Message;
            }
            return result;
        }

        /// <summary>
        /// 获取该名用户的缴费充值记录
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="meterNumber"></param>
        /// <returns></returns>
        public Task<List<WxSrOrderRecords>> ChargingRecords(string openId, string meterNumber)
        {
            var array = _wxRechargeRead.SelectOrders(openId, meterNumber)
                .Where(o => o.OrderStatus == (int)OrderStatus.Finish)
                .OrderByDescending(o => o.CreateTime).ToList();
            return Task.Run(() => array);
        }

        /// <summary>
        /// 修改订单状态
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="out_trade_no"></param>
        /// <param name="orderstatus"></param>
        /// <returns></returns>
        public BooleanResult UpdataOrderState(string openid, string out_trade_no,
            OrderStatus orderstatus)
        {
            var result = new BooleanResult { Success = false };
            try
            {
                var order = _wxRechargeRead.SelectOrder(openid, out_trade_no);
                order.OrderStatus = (int)orderstatus;
                try
                {
                    result.Success = _wxRechargeWrite.UpdataOrder(order);
                    if (!result.Success)
                        result.ErrorMessage = "修改表单状态失败";
                }
                catch (Exception e)
                {
                    _logger.Error(e);
                    result.ErrorMessage = e.Message;
                }
            }
            catch (SqlNullValueException e)
            {
                _logger.Error(e);
                result.ErrorMessage = e.Message;
            }
            return result;
        }
    }
}